package com.xuecheng;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

/**
 * @author hjh
 * @Description TODO
 * @since 2023/5/12
 */

@SpringBootTest
@SpringJUnitConfig(classes = AuthApplication.class)
public class test {
	
	@Autowired
	ApplicationContext applicationContext;
	
	@Test
	void test1(){
		String password = "111111";
		PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		for(int i=0;i<10;i++) {
			//每个计算出的Hash值都不一样
			String hashPass = passwordEncoder.encode(password);
			System.out.println(hashPass);
			//虽然每次计算的密码Hash值不一样但是校验是通过的
			boolean f = passwordEncoder.matches(password, hashPass);
			System.out.println(f);
		}
	}
	@Test
	void test2(){
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String usertoken =(String) authentication.getCredentials();
		System.out.println(usertoken);
	}
	
	@Test
	void test3(){
		// 获取AuthenticationManager对象
		AuthenticationManager authenticationManager = applicationContext.getBean(AuthenticationManager.class);
		// 定义一个用户名和密码
		String username = "zhangsan";
		String password = "123";
		// 构建一个包含用户名和密码的Token令牌
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
		// 通过AuthenticationManager进行认证，返回一个认证过的Token令牌
		Authentication authentication = authenticationManager.authenticate(token);
		// 从认证信息中获取token值
		String authToken = (String) authentication.getCredentials();
		System.out.println(authToken);
	}
}
